/*    This file is part of libmissive.
 *
 *    libmissive is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    libmissive is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with libmissive.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <stdlib.h>
#include <string.h>

#include "sign.h"

int
msg_sign(Msg *msg, const Sign_skey their_skey)
{
        unsigned long long sign_len = msg->len + crypto_sign_BYTES;
	unsigned char *signed_buf = malloc(sign_len);

	if (!signed_buf)
		return -1;

	if (crypto_sign(signed_buf, &sign_len, msg->buf,
			msg->len, their_skey)) {
		free(signed_buf);
		return -1;
	}

	msg_dispose(msg);
	msg_send_init(msg, sign_len, signed_buf, 1);
	return 0;
}

int
msg_sign_open(Msg *msg, const Sign_pkey their_pkey)
{
	unsigned char *unsigned_buf;
	unsigned long long unsign_len;

	if (msg->len < crypto_sign_BYTES)
		return -1;

	if (!(unsigned_buf = malloc(msg->len - crypto_sign_BYTES)))
		return -1;

	if (crypto_sign_open(unsigned_buf, &unsign_len,
			     msg->buf, msg->len, their_pkey)) {
		free(unsigned_buf);
		return -1;
	}

	msg_dispose(msg);
	msg_send_init(msg, unsign_len, unsigned_buf, 1);
	return 0;
}

int
signer_add(Msg *msg, const Sign_pkey my_pkey)
{
	size_t len = msg->len + sizeof(Sign_pkey);
        unsigned char *buf = realloc(msg->buf, len);

	if (!buf)
		return -1;

	memcpy(buf + msg->len, my_pkey, sizeof(Sign_pkey));
	msg->buf = buf;
	msg->len = len;
	return 0;
}

int
signer_remove(Msg *msg, Sign_pkey their_pkey)
{
	if (signer_get(msg, their_pkey) < 0)
		return -1;

	msg->len -= sizeof(Sign_pkey);
	return 0;
}

int
signer_get(const Msg *msg, Sign_pkey their_pkey)
{
	if (msg->len < sizeof(Sign_pkey))
		return -1;

	if (their_pkey)
		memcpy(their_pkey,
		       (char *) msg->buf + msg->len - sizeof(Sign_pkey),
		       sizeof(Sign_pkey));

	return 0;
}

int
signer_open(Msg *msg, Sign_pkey their_pkey)
{
	Err err;
	Msg copy;
	Sign_pkey tmp;

	if (!their_pkey)
		their_pkey = tmp;

	if (msg_copy(&copy, msg, &err) < 0)
		return -1;

	if (signer_remove(&copy, their_pkey) < 0 ||
	    msg_sign_open(&copy, their_pkey)) {
		msg_dispose(&copy);
		return -1;
	}

	msg_dispose(msg);
	*msg = copy;
	return 0;
}
